import json
import os
import shutil
import threading
import time

import pandas as pd
import requests
import streamlit as st
import pymysql
import random
import datetime

from tags import tags

MYSQL_HOST = "127.0.0.1"
MYSQL_PORT = 3306
MYSQL_USER = "root"
MYSQL_PASSWORD = "G5v3m5e5!"
MYSQL_DB = "random_tag_ygo"

REROLL = 1

st.set_page_config(
    page_title="厄厄杯-线上娱乐赛",
    page_icon="👋",
)

hide_streamlit_style = """
    <style>
        .reportview-container {
            margin-top: -2em;
        }
        #MainMenu {visibility: hidden;}
        .stDeployButton {display:none;}
        footer {visibility: hidden;}
        #stDecoration {display:none;}
    </style>
            """
st.markdown(hide_streamlit_style, unsafe_allow_html=True)

# 连接MySQL数据库
conn = pymysql.connect(
    host=MYSQL_HOST,
    port=MYSQL_PORT,
    user=MYSQL_USER,
    password=MYSQL_PASSWORD,
    database=MYSQL_DB
)

# 创建游标
cursor = conn.cursor()

# 创建user_data表（如果不存在）
cursor.execute("""
    CREATE TABLE IF NOT EXISTS random_tags (
        id INT AUTO_INCREMENT PRIMARY KEY,
        username VARCHAR(255) UNIQUE,
        elements VARCHAR(255),
        verify_code VARCHAR(255),
        created_at DATE DEFAULT (CURRENT_DATE)
    )
""")

# 创建user_data表（如果不存在）
cursor.execute("""
    CREATE TABLE IF NOT EXISTS deck_info (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(255) UNIQUE,
    created_at DATE DEFAULT (CURRENT_DATE)
    )
""")

# 创建user_data表（如果不存在）
cursor.execute("""
    CREATE TABLE IF NOT EXISTS player_confirm (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(255) UNIQUE,
    created_at DATE DEFAULT (CURRENT_DATE)
    )
""")

# Streamlit应用程序
st.markdown("<h1 style='text-align: center;'>🎉厄厄杯-线上娱乐赛🎉</h1>", unsafe_allow_html=True)

# 设定目标日期
target_date = datetime.datetime(2024, 2, 5,13,0)

now = datetime.datetime.now()
countdown = target_date - now

# 格式化显示倒计时
days = countdown.days
hours, remainder = divmod(countdown.seconds, 3600)
minutes, seconds = divmod(remainder, 60)

# 创建一个自定义的HTML和CSS样式
badge_html = """
<div style="
    border: 3px solid #B8860B; 
    border-radius: 15px; 
    text-align: center; 
    color: #B8860B; 
    font-size: 24px; 
    padding: 5px; 
    width: 200px;
    margin: auto;">
    测试阶段
</div>
"""

# 在Streamlit应用中显示它
st.markdown(badge_html, unsafe_allow_html=True)

# 使用Markdown和HTML创建简约的倒计时显示
st.markdown(
    f"<h4 style='text-align: center;'>⏱ 距离比赛还有 : {days} 天 {hours} 小时</h2>",
    unsafe_allow_html=True)

st.markdown('''
请在输入框输入报名时的昵称和报名成功显示的验证码来查看报名信息。
''')

# 输入框和按钮
username = st.text_input("请输入比赛昵称:")
verify = st.text_input("请输入验证码:")

button1 = st.button("查询")

if 'stage' not in st.session_state:
    st.session_state.stage = 0

if button1:
    # 查询数据库
    if not username or username == "":
        st.error(f"用户名不能为空 ")
    else:
        cursor.execute("SELECT * FROM random_tags WHERE username=%s", (username,))
        existing_data = cursor.fetchone()
        if existing_data:
            code = existing_data[3]
            if code == verify:
                elements = str(existing_data[2]).replace(" ","").split(',')
                st.success("查询成功！")
                st.markdown(f"选手：**{username}** ")
                st.markdown(f"抽选的字段是：")
                # 创建两列布局
                pic1 ,pic2, pic3 = st.columns(3)
                # 在第一列显示图片
                with pic1:
                    st.image(f"img/card/cut_{elements[0]}.jpg", use_column_width= "auto" ,caption=elements[0])
                # 在第一列显示图片
                with pic2:
                    st.image(f"img/card/cut_{elements[1]}.jpg", use_column_width= "auto",caption=elements[1])
                # 在第一列显示图片
                with pic3:
                    st.image(f"img/card/cut_{elements[2]}.jpg", use_column_width= "auto",caption=elements[2])
                cursor.execute("SELECT * FROM deck_info WHERE username=%s", (username,))
                ud = cursor.fetchone()
                if ud:
                    st.markdown('''
                        <div style="color:green">
                            已提交卡组。
                        </div>
                        ''', unsafe_allow_html=True)
                    st.session_state.stage = 1
                else:
                    st.markdown('''
                        <div style="color:red">
                            还未提交卡组。
                        </div>
                        ''', unsafe_allow_html=True)


            else:
                st.error(f"选手 **{username}** 验证码不正确！")
        else:
            st.error(f"选手 **{username}** 不存在！")

if st.session_state.stage == 1:
    target_path = '/root/random_server/srvpro/decks'
    # target_path = 'E:/workspace/random-field-backend/deck'
    source_path = '/root/random-field-backend/deck'
    if os.path.exists(os.path.join(target_path,f"{username}.ydk")):
        st.markdown('''
                            <div style="color:green">
                                已确认参赛。 
                            </div>
                            ''', unsafe_allow_html=True)
        url = 'http://127.0.0.1:5000/deck_info'
        data = {'username': username}
        # 发送POST请求
        headers = {'Content-Type': 'application/json'}
        response = requests.post(url, headers=headers, data=json.dumps(data, ensure_ascii=True))

        response.encoding = 'utf-8'
        content = json.loads(response.text)
        # 检查响应状态码
        if response.status_code == 200:
            print("POST请求成功")
            print("响应内容：", content)
            res_infos = content
            if res_infos['res'] is True:
                df_extra = pd.DataFrame(list(res_infos['content']['extra'].items()), columns=['卡名', '数量'])
                df_main = pd.DataFrame(list(res_infos['content']['main'].items()), columns=['卡名', '数量'])
                df_side = pd.DataFrame(list(res_infos['content']['side'].items()), columns=['卡名', '数量'])
                st.markdown("<h3 style='text-align: center;'>比赛卡组详情</h3>", unsafe_allow_html=True)
                main_count,extra_count,side_count = st.columns(3)
                with main_count:
                    st.metric("主卡组",f"{str(sum(list(res_infos['content']['main'].values())))}张")
                with extra_count:
                    st.metric("额外卡组",f"{str(sum(list(res_infos['content']['extra'].values())))}张")
                with side_count:
                    st.metric("副卡组",f"{str(sum(list(res_infos['content']['side'].values())))}张")
                st.markdown('主卡组')
                st.dataframe(df_main,hide_index=True,use_container_width=True)
                st.markdown('额外卡组')
                st.dataframe(df_extra,hide_index=True,use_container_width=True)
                st.markdown('副卡组')
                st.dataframe(df_side,hide_index=True,use_container_width=True)

        b = st.button("重新确认")
    else:
        b = st.button("确认参赛")
    if b:
        if not os.path.exists(os.path.join(source_path,f"{username}.ydk")):
            st.error("未知错误，请联系管理员")
        shutil.copy(os.path.join(source_path,f"{username}.ydk"), target_path)
        # 指定要请求的URL
        url = 'http://8.130.89.246:8003/api/upload_to_challonge?username=root&password=g5v3m5e5'

        # 发送GET请求
        response = requests.get(url)

        # 检查请求是否成功
        if response.status_code == 200:
            print('更新锦标赛成功！')
            # 打印响应的内容
            print(response.text)
        else:
            st.error(f'更新锦标赛失败，状态码：{response.status_code}')
        st.success("确认参赛成功！请重新查询！")
        st.session_state.stage = 0
        time.sleep(2)
        st.rerun()
# 关闭数据库连接
cursor.close()
conn.close()
